<template>
  <business-layout title='暖通系统设备'>
    <div class='table-page-search-wrapper' slot='query'>
      <a-row style='height: 40px;'>
        <a-form style='height: 40px;' :form='form' layout='inline' @submit='handleQueryData'>
          <a-col :span='4' style='height: 40px;'>
            <a-form-item style='width: 100%'>
              <a-input style='width: 100%' v-model='queryParam.username' placeholder='请输入设备名称或者生产厂家' />
            </a-form-item>
          </a-col>
          <a-col :span='6' style='height: 40px;margin-left: 10px'>
            <a-form-item>
              <a-button type='primary' html-type='submit'>
                <a-icon type='search' />
                查询
              </a-button>
              <a-button html-type='reset' style='margin-left: 10px;' @click='handleResetData'>
                重置
              </a-button>
            </a-form-item>
          </a-col>
        </a-form>
      </a-row>
    </div>

    <template slot='btns'>
      <a-button type='primary' icon='plus' @click='handleAdd'>新建</a-button>
      <a-button type='primary' style='margin-right: 10px' @click='importVisable = true'>
        <a-icon type='cloud-upload' />
        导入
      </a-button>
      <a-dropdown v-if='selectedRowKeys.length > 0' style='margin-right: 10px'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='handleDeletes'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
          <a-menu-item key='2' @click='handleExportData'>
            <a-icon type='download' />
            导出所选
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'>
          批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
    </template>

    <s-table
      ref='table'
      size='default'
      rowKey='id'
      :columns='columns'
      :data='loadData'
      :alert='true'
      :rowSelection='rowSelection'
      showPagination='auto'
      @change='onSelectChange'
    >
      <span slot='serial' slot-scope='text, record, index'>
        {{ index + 1 }}
      </span>
      <span slot='description' slot-scope='text'>
        <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
      </span>
      <span slot='installLocation' slot-scope='text'>
        <ellipsis :length='15' tooltip>{{ text }}</ellipsis>
      </span>

      <span slot='deviceType' slot-scope='text'>
        <ellipsis :length='10' tooltip>{{ text }}</ellipsis>
      </span>

      <span slot='action' slot-scope='text, record'>
        <template>
          <a @click='handleEdit(record)'>编辑</a>
          <a-divider type='vertical' />
          <a class='del-link' @click='handleSub(record)'>删除</a>
        </template>
      </span>
    </s-table>

    <create-form
      ref='createModal'
      :visible='visible'
      :loading='confirmLoading'
      :model='mdl'
      @cancel='handleCancel'
      @ok='handleOk'
    />
    <import-dialog
      :import-params='importParams'
      :importFileFun='importFun'
      template-path='money/暖通系统资产设备模板.xlsx'
      :visible='importVisable'
      @close='importVisable = false'
      @refsh='handleRefsh'
    />
  </business-layout>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'

import CreateForm from './modules/CreateForm'
import {
  descriptions,
  updateDevices,
  deleteDevices,
  findBypages,
  batchDeletes,
  importExcals,
  exportExcel
} from '@/api/description'
import ImportDialog from '@/components/ImportDialog/index.vue'

const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '名称',
    dataIndex: 'deviceName'
  },
  {
    title: '设备目录',
    dataIndex: 'deviceDirectory'
  },
  {
    title: '设备编号',
    dataIndex: 'deviceNo'
  },
  {
    title: '安装位置',
    dataIndex: 'installLocation',
    scopedSlots: { customRender: 'installLocation' }
  },
  {
    title: '安装日期',
    dataIndex: 'installDate'
  },
  {
    title: '投运日期',
    dataIndex: 'useDate'
  },
  {
    title: '设备型号',
    dataIndex: 'deviceType',
    scopedSlots: { customRender: 'deviceType' }
  },
  {
    title: '生产厂家',
    dataIndex: 'producer'
  },
  {
    title: '厂家联系人',
    dataIndex: 'contactPerson'
  },
  {
    title: '厂家联系电话',
    dataIndex: 'producerPhone'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'TableList',
  components: {
    ImportDialog,
    STable,
    Ellipsis,
    CreateForm
  },
  data () {
    this.columns = columns

    return {
      importVisable: false,
      activeKey: '1',
      // create model
      visible: false,
      form: this.$form.createForm(this),
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return findBypages({ ...requestParameters, pageType: 2 })
          .then(res => {
            return res
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      importParams: {
        pageType: 2
      }
    }
  },
  filters: {},

  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    importFun: importExcals,
    exportData () {
      exportExcel({ pageType: 2 })
    },
    handleRefsh () {
      this.$refs.table.refresh()
    },
    handleResetData () {
      this.queryParam = {}
      this.$refs.table.refresh()
    },
    handleQueryData (e) {
      e.preventDefault()
      const form = this.form
      const that = this
      const queryObj = {}
      form.validateFields((error, values) => {
        Object.keys(values).forEach(key => {
          if (values[key]) {
            queryObj[key] = values[key]
          }
        })
        this.queryParam = queryObj
        that.$refs.table.refresh()
      })
    },
    handleAdd () {
      this.mdl = null
      this.visible = true
    },
    handleEdit (record) {
      this.visible = true
      this.mdl = { ...record }
      console.log(this.mdl, 'this.mdl')
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if (this.mdl && this.mdl.id > 0) {
            let updates = Object.assign(this.mdl, values)
            updateDevices(updates).then(Res => {
              this.visible = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('更新成功')
            }).finally(() => {
              this.confirmLoading = false
            })
          } else {
            // 新增
            descriptions({ ...values, pageType: 2 }).then(Res => {
              this.visible = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()

              this.$message.success('新增成功')
            }).finally(() => {
              this.confirmLoading = false
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub (record) {
      const that = this
      this.$confirm({
        title: '提示?',
        content: '当前操作不可逆、是否继续？',
        okType: 'danger',
        async onOk () {
          const result = await deleteDevices(record.id)
          if (result) {
            that.$message.success('删除成功')
            that.$refs.table.refresh()
          }
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleExportData () {
      let ids = []
      this.selectedRows.forEach(item => {
        ids.push(item.id)
      })
      exportExcel({ ids: this.$refs.table.selectedRowKeys.join(','), pageType: 2 })
    },
    handleDeletes () {
      const that = this
      this.$confirm({
        title: '提示?',
        content: '当前操作不可逆、是否继续？',
        okType: 'danger',
        async onOk () {
          const result = await batchDeletes(that.$refs.table.selectedRowKeys)
          if (result) {
            that.$message.success('删除成功')
            that.$refs.table.clearSelected()
            that.$refs.table.refresh()
          }
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
<style lang='less' scoped>
.table-tab {

}
</style>
